package com.lei.springbootpractice.controller;

import com.lei.springbootpractice.service.ImageService;
import com.lei.springbootpractice.service.ProductsService;
import com.lei.springbootpractice.pojo.ProductsPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图片管理控制器
 * 提供图片相关的API接口
 */
@RestController
@RequestMapping("/api/images")
public class ImageController {

    @Autowired
    private ImageService imageService;

    @Autowired
    private ProductsService productsService;

    /**
     * 获取图片信息
     */
    @GetMapping("/info/{productId}")
    public Map<String, Object> getImageInfo(@PathVariable String productId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            ProductsPojo product = productsService.getProductById(productId);
            if (product == null) {
                result.put("status", "error");
                result.put("message", "商品不存在");
                return result;
            }
            
            if (product.getPhoto() == null || product.getPhoto().isEmpty()) {
                result.put("status", "info");
                result.put("message", "该商品没有图片");
                return result;
            }
            
            // 验证Base64图片数据
            if (!imageService.isValidBase64Image(product.getPhoto())) {
                result.put("status", "error");
                result.put("message", "图片数据格式无效");
                return result;
            }
            
            // 获取图片信息
            ImageService.ImageInfo imageInfo = imageService.getImageInfo(product.getPhoto());
            
            result.put("status", "success");
            result.put("productId", productId);
            result.put("productName", product.getProductName());
            result.put("imageInfo", Map.of(
                "width", imageInfo.getWidth(),
                "height", imageInfo.getHeight(),
                "fileSize", imageInfo.getFileSize(),
                "fileSizeFormatted", imageInfo.getFileSizeFormatted(),
                "base64Length", product.getPhoto().length()
            ));
            
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "获取图片信息失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 统计所有商品图片信息
     */
    @GetMapping("/statistics")
    public Map<String, Object> getImageStatistics() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<ProductsPojo> products = productsService.getAllProducts();
            
            int totalProducts = products.size();
            int productsWithImages = 0;
            int productsWithoutImages = 0;
            int validImages = 0;
            int invalidImages = 0;
            long totalImageSize = 0;
            
            for (ProductsPojo product : products) {
                if (product.getPhoto() != null && !product.getPhoto().isEmpty()) {
                    productsWithImages++;
                    
                    try {
                        if (imageService.isValidBase64Image(product.getPhoto())) {
                            validImages++;
                            ImageService.ImageInfo imageInfo = imageService.getImageInfo(product.getPhoto());
                            totalImageSize += imageInfo.getFileSize();
                        } else {
                            invalidImages++;
                        }
                    } catch (Exception e) {
                        invalidImages++;
                    }
                } else {
                    productsWithoutImages++;
                }
            }
            
            result.put("status", "success");
            result.put("statistics", Map.of(
                "totalProducts", totalProducts,
                "productsWithImages", productsWithImages,
                "productsWithoutImages", productsWithoutImages,
                "validImages", validImages,
                "invalidImages", invalidImages,
                "totalImageSize", totalImageSize,
                "totalImageSizeFormatted", formatFileSize(totalImageSize),
                "averageImageSize", productsWithImages > 0 ? totalImageSize / productsWithImages : 0
            ));
            
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "获取统计信息失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 验证所有商品图片
     */
    @PostMapping("/validate-all")
    public Map<String, Object> validateAllImages() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<ProductsPojo> products = productsService.getAllProducts();
            Map<String, Object> validationResults = new HashMap<>();
            
            for (ProductsPojo product : products) {
                Map<String, Object> productResult = new HashMap<>();
                productResult.put("productName", product.getProductName());
                
                if (product.getPhoto() == null || product.getPhoto().isEmpty()) {
                    productResult.put("status", "no_image");
                    productResult.put("message", "没有图片");
                } else {
                    try {
                        if (imageService.isValidBase64Image(product.getPhoto())) {
                            ImageService.ImageInfo imageInfo = imageService.getImageInfo(product.getPhoto());
                            productResult.put("status", "valid");
                            productResult.put("message", "图片有效");
                            productResult.put("imageInfo", Map.of(
                                "width", imageInfo.getWidth(),
                                "height", imageInfo.getHeight(),
                                "fileSize", imageInfo.getFileSizeFormatted()
                            ));
                        } else {
                            productResult.put("status", "invalid");
                            productResult.put("message", "图片数据无效");
                        }
                    } catch (Exception e) {
                        productResult.put("status", "error");
                        productResult.put("message", "验证失败：" + e.getMessage());
                    }
                }
                
                validationResults.put(product.getProductId(), productResult);
            }
            
            result.put("status", "success");
            result.put("message", "验证完成");
            result.put("results", validationResults);
            
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "验证失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 格式化文件大小
     */
    private String formatFileSize(long bytes) {
        if (bytes < 1024) return bytes + " B";
        if (bytes < 1024 * 1024) return String.format("%.1f KB", bytes / 1024.0);
        return String.format("%.1f MB", bytes / (1024.0 * 1024.0));
    }
} 